/**
 * @name 操作对象
 */

import { PublicInterface } from '@/interface/public';

/**
 * 根据原对象设置新对象值
 * @param obj 原对象
 * @param str 新对象值
 * @returns 新的对象
 */
export const objSetNewObjValue = (obj: PublicInterface['UnknownObjProps'], str: string) => {
  const arr = str.split(',');
  let newObj: any = {};
  for (let key of arr) {
    newObj[key] = obj[key];
  }
  return newObj;
};

/**
 * @description 将对象内的key添加指定前缀
 */
export function objAddPrefix(obj: object = {}, flag: string = 'm_') {
  if (!obj) return {};
  const newObj: any = {};
  Object.keys(obj).forEach(key => {
    if (isValidKey(key, obj)) {
      newObj[flag + key] = obj[key];
    }
  });

  return newObj;
}

/** 根据路径获取对象对应属性值  childrenProps.apiParams.url*/
export function getNestedValue(obj: any, path: string): any {
  return path.split('.').reduce((acc, key) => acc && acc[key], obj);
}
/** 根据对象路径设置值 */
export function setNestedValue(obj: any, path: string, value: any, flag: boolean = true): void {
  const keys = path.split('.');
  const lastKey = keys[keys.length - 1];

  // 仅有一个键，直接设置值
  if (flag && keys.length <= 1) {
    obj[lastKey] = value;
  }

  if (!lastKey) {
    return;
  }

  const v = keys.slice(0, -1).reduce((acc, key) => {
    if (!acc[key]) {
      acc[key] = {};
    }
    return acc[key];
  }, obj);

  // // 检查目标位置是否已经有值
  // if (v[lastKey] === undefined) {

  v[lastKey] = value;
  // }
}
